var app=getApp();
Page({
  onLoad(e){
    let card = wx.getStorageSync('buycard');
    console.log(card.price);
    card.price = parseFloat(card.price) || card.price;
    card.deposit = parseFloat(card.deposit)||card.deposit;
    card.goods_type = parseInt(card.card_id)+1;
    this.setData({ card: card, jianyajin: e.jianyajin || "", olddeposit: card.olddeposit});
    wx.showLoading();
    this.youhuijuan();
    if(e.type === 'group'){
        var group={};
        if(e.group_type){//参团
            group.group_type = e.group_type;
        }
        if(e.group_id){//创团
            group.group_id = e.group_id;
        }
        this.setData({ group: group});
    }
    if (e.from === "pintuan" || e.from === "canjia"){
      this.zhima();
    }
    if (e.from === "canjia"){
      this.setData({ user_bargain_id: e.user_bargain_id})
    }
    let ctstartdate = app.setdate(0);
    let ctenddate = app.setdate(30);
    // if(card.rank===4){//无限次卡延期三月
    //   ctenddate = app.setdate(90);
    // }
    let ctdate = app.setdate(0);
    this.setData({ctdate: ctdate, ctstartdate: ctstartdate, ctenddate: ctenddate });
  },
  data:{
    num:1,
    youhuiprice: 0,//优惠价格
    haveyouhui: false,//有没有优惠卷
    hadyouhui: false,//选没选优惠卷
    coupon_no: '',//优惠券编号
    message:"",
    group:null
  },
  jia(e){
    this.setData({num:this.data.num+1});
  },
  jian(e){
    if(this.data.num<=1){return}
    this.setData({ num: this.data.num - 1 });
  },
  zhima(){
    let user_id = wx.getStorageSync('userdata').user_id;
    app.request('index/zhima/getUserZMScore', 'POST', { user_id: user_id }, 'zhimab', this)
  },
  zhimab(data){
    if (data.data.status == 0 || data.data.status==2) {
      this.setData({ jianyajin:'0'})
      return false
    }
    if (data.data.zmscore >= 600){
      this.setData({ jianyajin: '1', 'card.deposit':0})
    }
  },
  youhuijuan() {//查优惠卷
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('userdata').user_id;
    let goods_type = this.data.card.goods_type;
    let json = { token: token, userId: user_id, goods_type: goods_type, "type": '1'}
//    console.log(json)
    app.request('index/coupon/userCoupon', 'POST', json, 'youhuijuanb', this);
  },
  youhuijuanb(data) {//优惠查询回调
//    console.log(data);
    wx.hideLoading();
    if (data.code != 200) {
      return false;
    }
    if (data.data.length == 0) {
      this.setData({ youhuitext: '暂无可用红包' })
    } 
    else if (data.data.length == 1) {//一张默认选中
//      console.log(data.data)
      this.setData({
        youhuiprice: parseFloat(data.data[0].amount) || data.data[0].amount, youhuitext: data.data[0].coupon_name,
        coupon_no: data.data[0].coupon_no, haveyouhui: true, hadyouhui: true
      })
    }
    else if (data.data.length > 1) {
      this.setData({ youhuitext: data.data.length + '张可用', haveyouhui: true })
    }
  },
  checkyouhui(e) {//选择优惠卷
    if (this.data.haveyouhui) {
      wx.navigateTo({ url: '/pages/home/coupontype/coupontype?type=' + this.data.card.goods_type, })
    }
  },
  useyouhui(e) {//使用优惠卷,在优惠列表里选择了
    if (e == 'no') {
      this.setData({
        youhuiprice: 0, youhuitext: '不使用优惠',
        coupon_no: '', hadyouhui: false,
      })
      return false;
    }
    this.setData({
      youhuiprice: parseFloat(e.amount) || e.amount, youhuitext: e.name,
      coupon_no: e.coupon_no, hadyouhui: true
    })
  },
  message(e) {//留言
    this.setData({ message: e.detail.value });
  },
  buy(e){
    if (app.repeat(e.timeStamp) == false) { return; }
    
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('userdata').user_id;
    let card_id = this.data.card.card_id;
    let coupon_no = this.data.coupon_no;
    let num=this.data.num;
    let effect_day = this.data.ctdate;
    let cards = [{ "card_id": card_id, "zujie_coupon": coupon_no, "num": num }];   
    let _this=this;
    wx.showModal({
      title: '提示',
      content: '起始生效时间：' + effect_day,
      success(res){
        if(res.confirm){
          wx.showLoading({ title: '', mask: true })
          let json = { user_id: user_id, token: token, cards: cards, effect_day:effect_day }
          if (_this.data.group && _this.data.group.group_type) {
            json.group_type = _this.data.group.group_type;
          }
          if (_this.data.group && _this.data.group.group_id) {
            json.group_id = _this.data.group.group_id;
          }
          if (_this.data.user_bargain_id) {//砍价
            json.user_bargain_id = _this.data.user_bargain_id;
          }
          app.request('book/card/cardOrder', 'POST', json, 'buyb2', _this);
        }
      }
    })
    
  },
  gozm(e) {//去芝麻信用页
    if (app.repeat(e.timeStamp) == false) { return; }
    wx.redirectTo({ url: '/pages/home/zhima/zhima' })
  },
  buyb2(data){
//    console.log(data);
    if(data.code!=200){
      wx.hideLoading();
//      console.log(data);
      return
    }
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('userdata').user_id;
    let order_sn = data.data.order_sn;
//    console.log(order_sn);
    let openId = wx.getStorageSync('openid');
    let json = {
      token: token, userId: user_id, orderSn: order_sn, payMethod: 5, "type": 2, openId: openId
    }
//    console.log(json);
    app.payrequest('pay/jsapi/cardPay', 'POST',json,'pay',this)
  },
  pay(data){
//    console.log(data);
    wx.hideLoading();
    if (data.code && data.code == 300) {
      wx.showToast({ title: data.msg, mask: true, duration: 1000, icon: 'none' });
      return false
    }
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType,
      'paySign': data.paySign,
      success(e) {
        wx.showToast({ title: '购买成功！', icon: 'success', mask: true, duration: 1000 });
        let pages = getCurrentPages();//页面栈
        if(pages.length >= 3){
            var prevPage = pages[pages.length - 3];//mycard-Page对象
            if (prevPage.buynewcard) {
              prevPage.buynewcard();//刷新我的会员计划页面
            }
        }
        setTimeout(() => {          
          wx.navigateBack({ delta: 1 })
        }, 1000)
      },
      fail(e) {
        wx.showToast({ title: '支付取消', mask: true, duration: 1000,icon:'none'});
        setTimeout(() => {
          wx.navigateBack({ delta: 1 })
        }, 1000)
      }
    })
    let token = wx.getStorageSync('token');
    let user_id = wx.getStorageSync('userdata').user_id;
    app.request('book/user/bookShelfNum', 'POST', { token: token, user_id: user_id }, 'shelfnum', app);
  },
  bindDateChoose(e) {//修改开卡日期
    this.setData({ ctdate: e.detail.value});
  }
})